<template>
  <el-select
    v-model="comValue"
    :disabled="disabled"
    :placeholder="placeholder"
    :style="{ width: width }"
    :clearable="clearable"
    :filterable ="isFilterAble"
    @change="change"
  >
    <el-option
      v-for="item in options"
      :key="item.code"
      :label="item.name"
      :value="item.code"
      :disabled="item.disabled"
    />
  </el-select>
</template>

<script setup>
import { watch, computed, ref } from 'vue'
import { dictStore } from '@/pinia/modules/dict'
const dictStoreData = dictStore()
const emit = defineEmits(['update:modelValue', 'change'])
const props = defineProps({
  modelValue: {
    type: [String, Number],
    require: true,
    default: ''
  },
  dictCode: {
    require: true,
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  width: {
    type: String,
    default: '160px'
  },
  clearable: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  disabledOptions: {
    type: Array,
    default() {
      return []
    }
  },
  sourceFrom: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'String'
  },
  isFilterAble: {
    type: Boolean,
    default: false
  }
})
const comValue = ref('')
const options = computed(() => {
  return formatDictCode()
})
watch(
  () => props.modelValue,
  val => {
    if (val || val === 0) {
      comValue.value = props.type === 'Number' ? val : val + ''
    } else {
      comValue.value = ''
    }
  },
  {
    immediate: true
  }
)

watch(
  () => comValue.value,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      emit('update:modelValue', newVal)
    }
  }
)

const formatDictCode = () => {
  const code = props.dictCode
  const target = dictStoreData.dict.find(item => item.code === code)
  // debugger
  if (target && props.disabledOptions.length > 0) {
    const extraTarget = []
    target.children.map(item => {
      if (props.disabledOptions.find(item1 => item.code == item1)) {
        extraTarget.push({
          ...item,
          disabled: true
        })
      } else {
        extraTarget.push({
          ...item
        })
      }
    })
    return extraTarget
  }

  return target
    ? props.type === 'Number'
      ? target.children.map(item => {
          return {
            ...item,
            code: Number(item.code)
          }
        })
      : target.children
    : []
}

const change = val => {
  const obj = options.value.find(item => {
    return item.code == val
  })
  emit('change', obj)
}
</script>

<style></style>
